<template>
  <div>
    <Row :gutter="24">
      <Col span="6">
        <Card title="图片空间管理">
          <div style="margin-left: -8px">
            <Button
              type="info"
              :disabled="noAdd"
              @click="add()"
              class="ivu-ml-8 ivu-mt-8"
              v-if="showBtn('新增子分类')"
              >新增子分类</Button
            >
            <Button
              type="info"
              @click="add(true)"
              class="ivu-ml-8 ivu-mt-8"
              v-if="showBtn('新增根分类')"
              >新增根分类</Button
            >
            <Button
              class="ivu-ml-8 ivu-mt-8"
              @click="edit()"
              :disabled="isDisabled"
              v-if="showBtn('编辑')"
              >编辑</Button
            >
            <Button
              class="ivu-ml-8 ivu-mt-8"
              @click="delClassify()"
              :disabled="isDisabled"
              v-if="showBtn('删除')"
              >删除</Button
            >
          </div>
          <div class="tree">
            <Tree :data="baseData" @on-select-change="treeSelectChange"></Tree>
            <Spin size="large" fix v-if="treeSpinShow"></Spin>
          </div>
        </Card>
      </Col>
      <Col span="18">
        <Card
          title="我的图片"
          v-show="key !== '-1'"
          :bordered="false"
          dis-hover
          class="ivu-mt"
        >
          <div slot="extra">
            <file-upload
              :apiData="upLoadData"
              :fileData="fileData"
              :fileCon="fileCon"
              @handleChange="getImageList"
            ></file-upload>
          </div>
          <div class="qw-imgbox">
            <div class="qw-noimg-box" v-if="imgList.length === 0">
              <Icon type="ios-images-outline" />
              暂未上传图片
            </div>
            <Row v-else :gutter="24">
              <Col
                v-for="(item, index) in imgList"
                :key="index"
                :xxl="6"
                :xl="8"
                :lg="8"
                :md="12"
                :sm="24"
                :xs="24"
                class="ivu-mb"
              >
                <!-- <i-link :to="item.link" target="_blank"> -->
                <Card :bordered="false" class="goods-list-item">
                  <div class="goods-list-item-img">
                    <img :src="item.url" alt="cover" />
                  </div>
                  <div
                    class="goods-list-item-title"
                    style="
                      width: 245px;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                      overflow: hidden;
                    "
                  >
                    {{ item.imageName }}
                  </div>
                  <div class="goods-list-item-desc qw-disflex">
                    <p class="qw-flex">{{ item.imageSize }}</p>
                    <p>{{ item.imageSpace }}</p>
                    <p style="margin-left: 20px" @click="delImage(item.uuid)">
                      删除
                    </p>
                  </div>
                </Card>
                <!-- </i-link> -->
              </Col>
            </Row>
            <Spin size="large" fix v-if="spinShow"></Spin>
          </div>
          <!-- 分页 start  -->
          <div class="ivu-mt ivu-text-center" v-show="imgList.length > 0">
            <Page
              :total="totalNum"
              show-total
              show-sizer
              :current.sync="nowPage"
              @on-change="getImageList"
              @on-page-size-change="handleChangePage"
            />
          </div>
          <!-- 分页 end  -->
        </Card>
      </Col>
    </Row>
    <!-- 新增、更新分类 start -->
    <Modal v-model="classShow" :title="classifyTypeTxt + '分类'">
      <Row>
        <Col span="22">
          <Form
            ref="classifyForm"
            :model="classifyFormData"
            :rules="classifyFormRules"
            :label-width="100"
          >
            <FormItem label="分类名称：" prop="categoryName">
              <Input
                v-model="classifyFormData.categoryName"
                maxlength="10"
                show-word-limit
                placeholder="请输入分类名称"
              />
            </FormItem>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button
          type="primary"
          :loading="sLoading"
          @click.stop="handleAgree('classifyForm')"
          >确定</Button
        >
        <Button type="default" @click.stop="handleCancel('classifyForm')"
          >取消</Button
        >
      </div>
    </Modal>
    <!-- 新增、更新分类 end -->
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { mapGetters } from 'vuex';
import fileUpload from '@/components/common/fileUpload'; // fileUpload
import { getBtnsId } from '@/libs/btnsPermission';
export default {
  components: { fileUpload },
  data () {
    return {
      upLoadData: {},
      fileCon: {
        type: 'select', // 上传控件的类型，可选值为 select（点击选择），drag（支持拖拽）
        showUploadList: true,
        multiple: false, // 是否支持多选文件
        format: ['jpg', 'jpeg', 'png'], // 支持的文件类型
        maxSize: 2048, // 文件大小限制，单位 kb Number
        maxLen: '9999' // 文件数量限制
      },
      fileData: [],
      imgList: [],
      nowPage: 1, // 当前页
      totalNum: 0, // 总条数
      pageShow: 10, // 每页展示条数
      baseData: [],
      isDisabled: true,
      treeSpinShow: false,
      isAdd: true,
      spinShow: false,
      noAdd: false,
      key: '-1', // -1//当前uuid
      isRoot: true, // 根目录
      sLoading: false,
      classShow: false,
      classifyTypeTxt: '新增',
      classifyFormData: {
        categoryName: ''
      },
      classifyFormRules: {
        categoryName: [
          { required: true, message: '请输入图片分类名称', trigger: 'blur' }
        ]
      },
      requestApi: {
        // 根据级别及父分类uuid获取选择的分类列表信息
        getImageList: {
          url: '/sysback/platimagelibrary/toImageList',
          type: 'post' // 接口请求类型
        },
        // 获取分类树列表
        getNodes: {
          url: '/sysback/platimagecategory/getNodes',
          type: 'post' // 接口请求类型
        },
        // 新增分类内容
        addClassify: {
          url: '/sysback/platimagecategory/save',
          type: 'post' // 接口请求类型
        },
        // 更新分类内容
        updateCategory: {
          url: '/sysback/platimagecategory/updateCategory',
          type: 'post' // 接口请求类型
        },
        // 校验是否可以删除分类
        checkRelation: {
          url: '/sysback/productstorecategoryrel/checkRelation',
          type: 'post' // 接口请求类型
        },
        // 删除该分类内容
        delClassify: {
          url: '/sysback/platimagecategory/deleteCategory',
          type: 'post' // 接口请求类型
        },
        // 删除图片
        deleteImage: {
          url: '/sysback/platimagelibrary/deleteImage',
          type: 'post' // 接口请求类型
        }
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  watch: {
    key (n, o) {
      this.upLoadData = {
        categoryUuid: n
      };
    }
  },
  created () {
    this.getNodes();
  },
  methods: {
    getData () {},
    // 切换分页
    handleChangePage (val) {
      this.pageShow = val;
      this.$nextTick(() => {
        this.getData();
      });
    },
    add (flag = false) {
      // flag:true(根分类)
      if (this.key === '-1' && !flag) {
        this.$Message.warning('请先选择分类');
        return false;
      }
      if (!flag) {
        let curBtnId = getBtnsId('新增根分类');
        sessionStorage.setItem('buttonId', curBtnId);
      } else {
        let curBtnId = getBtnsId('新增子分类');
        sessionStorage.setItem('buttonId', curBtnId);
      }
      this.classShow = true;
      this.classifyTypeTxt = '新增';
      this.isAdd = true;
      this.isRoot = flag;
      this.classifyFormData = {
        categoryName: ''
      };
      this.$nextTick(() => {
        this.$refs.classifyForm.resetFields();
      });
    },
    edit () {
      let curBtnId = getBtnsId('编辑');
      sessionStorage.setItem('buttonId', curBtnId);
      this.classShow = true;
      this.classifyTypeTxt = '编辑';
      this.isAdd = false;
    },
    // 获取分类树
    getNodes (uuid = '') {
      // let key = this.key;
      // if (uuid !== '') {
      //     key = uuid
      //     this.key = '-1';
      //     this.isDisabled = true;
      // }
      let data = {
        key: '-1'
      };
      this.treeSpinShow = true;
      ApiRequest(
        this.requestApi.getNodes.url,
        this.requestApi.getNodes.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          if (res.retData !== '' && res.retData !== []) {
            // let rData = JSON.parse(res.retData);
            this.baseData = res.retData;
          }
        }
        this.treeSpinShow = false;
      });
    },
    // 选择分类
    treeSelectChange (arr, item) {
      if (arr.length > 0) {
        this.isDisabled = false;
      } else {
        this.isDisabled = true;
      }
      if (item.parentUuid === '') {
        this.noAdd = false;
      } else {
        this.noAdd = true;
      }
      item.expand = !item.expand;
      this.key = item.key;
      // 表单置空
      // this.$nextTick(() => {
      this.$refs.classifyForm.resetFields();
      // })
      this.classifyFormData = {
        categoryName: item.title
      };
      this.getImageList();
    },
    // 获取分类图片列表
    getImageList () {
      this.spinShow = true;
      let data = {
        categoryUuid: this.key,
        nowPage: this.nowPage,
        pageShow: this.pageShow
      };
      ApiRequest(
        this.requestApi.getImageList.url,
        this.requestApi.getImageList.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          if (res.retData !== '') {
            // let rData = JSON.parse(res.retData);
            this.imgList = res.retData.results.map(item => ({
              ...item,
              url: `${this.IMAGEURL}${item.imageKey}?${this.XOSSPROCE}`
            }));
            this.totalNum = res.retData.totalNum;
          }
        }
        this.spinShow = false;
      });
    },
    // 提交
    handleAgree (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.sLoading) {
            return false;
          }
          this.sLoading = true;
          let data = {
            categoryName: this.classifyFormData.categoryName
          };
          let apiUrl = '';
          let apiType = '';
          if (this.isAdd) {
            apiUrl = this.requestApi.addClassify.url;
            apiType = this.requestApi.addClassify.type;
            data.parentUuid = this.isRoot ? '-1' : this.key;
            // 开始请求会员信息
            ApiRequest(
              this.requestApi.addClassify.url,
              this.requestApi.addClassify.type,
              data,
              true
            ).then(res => {
              if (res.retStatus === '1') {
                this.$Message.success('分类' + this.classifyTypeTxt + '成功!');
                this.classShow = false;
                // if (this.classifyFormData.uuid === '') {
                //     this.key = '-1';
                this.classifyFormData = {
                  categoryName: ''
                };
                this.$nextTick(() => {
                  this.$refs.classifyForm.resetFields();
                });
                this.getNodes('-1');
                // }
              }
              this.sLoading = false;
            });
          } else {
            apiUrl = this.requestApi.updateCategory.url;
            apiType = this.requestApi.updateCategory.type;
            data.selectUuid = this.key;
            // 开始请求会员信息
            ApiRequest(
              this.requestApi.updateCategory.url,
              this.requestApi.updateCategory.type,
              data,
              true
            ).then(res => {
              if (res.retStatus === '1') {
                this.$Message.success('分类' + this.classifyTypeTxt + '成功!');
                this.classShow = false;
                // if (this.classifyFormData.uuid === '') {
                //     this.key = '-1';
                this.classifyFormData = {
                  categoryName: ''
                };
                this.$nextTick(() => {
                  this.$refs.classifyForm.resetFields();
                });
                this.getNodes('-1');
                // }
              }
              this.sLoading = false;
            });
          }
        }
      });
    },
    handleCancel () {
      this.classShow = false;
    },
    // 校验是否可以删除分类
    checkRelation () {
      let data = {
        selectUuid: this.key
      };
      if (this.dLoading) {
        return false;
      }
      this.dLoading = true;
      // 开始请求会员信息
      ApiRequest(
        this.requestApi.checkRelation.url,
        this.requestApi.checkRelation.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          if (res.retData === 'false') {
            this.delClassify();
          } else {
            this.dLoading = false;
            this.$Message.warning('当前分类下存在关联的商品，不可删除');
          }
        } else {
          this.dLoading = false;
        }
      });
    },
    // 删除图片
    delImage (uuid) {
      this.$Modal.confirm({
        title: '删除操作',
        content: '确定要删除当前图片吗？',
        onOk: () => {
          let data = {
            uuid: uuid
          };

          // 开始请求会员信息
          ApiRequest(
            this.requestApi.deleteImage.url,
            this.requestApi.deleteImage.type,
            data,
            true
          ).then(res => {
            if (res.retStatus === '1') {
              this.getImageList();
            }
            this.dLoading = false;
          });
        }
      });
    },
    // 删除当前分类
    delClassify () {
      this.$Modal.confirm({
        title: '删除操作',
        content: '确定要删除当前分类吗？',
        onOk: () => {
          let curBtnId = getBtnsId('删除');
          sessionStorage.setItem('buttonId', curBtnId);
          let data = {
            selectUuid: this.key
          };

          // 开始请求会员信息
          ApiRequest(
            this.requestApi.delClassify.url,
            this.requestApi.delClassify.type,
            data,
            true
          ).then(res => {
            if (res.retStatus === '1') {
              if (res.retData === 'hasImage') {
                this.$Message.success('该分类不可以删除!');
              } else {
                this.$Message.success('分类删除成功!');
              }
              this.key = '-1';
              this.isDisabled = true;
              this.classifyFormData = {
                categoryName: ''
              };
              this.$nextTick(() => {
                this.$refs.classifyForm.resetFields();
              });
              this.getNodes();
            }
            this.dLoading = false;
          });
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.qw-imgbox {
  position: relative;
}

.qw-noimg-box {
  text-align: center;
  padding: 100px 0;
  color: #999;

  .ivu-icon-ios-images-outline {
    font-size: 100px;
    display: block;
    color: #eee;
    margin-bottom: 20px;
  }
}

.tree {
  border: 1px solid #eee;
  margin-top: 20px;
  margin-bottom: 30px;

  & /deep/ .ivu-tree {
    line-height: 26px;
  }
}

.ivu-col-offset-3 {
  margin-left: 0;
}

.ivu-mt,
.ivu-mt-16 {
  margin-top: 0 !important;
}

.order-price {
  text-align: right;

  b {
    color: #ed4014;
  }
}

.left {
  width: 45%;
  float: left;
  margin-right: 2%;
}

.right {
  float: left;
  width: 50%;
}

.goods-list-item {
  position: relative;
  border: 1px solid #f5f5f5;
}

.goods-list-item-img {
  background: #f5f5f5;
  font-size: 0;
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  position: relative;
}

.goods-list-item-img img {
  width: 100%;
  height: 100%;
  position: absolute;
}

.goods-list-item .ivu-tag {
  position: absolute;
  top: 10px;
  right: 10px;
}

.goods-list-item-title {
  font-size: 16px;
  font-weight: 700;
  margin: 8px 0;
}

.goods-list-item-desc {
  font-size: 14px;
  color: #808695;
}

.goods-list-item-price {
  font-size: 14px;
  color: #ff6700;
  margin: 8px 0;
}

.goods-list-item-price s {
  color: #c5c8ce;
}
</style>
